package upload

import (
	"github.com/worryry/8-pigeons/pkg/setting"
	util "github.com/worryry/8-pigeons/pkg/utils"
	"io"
	"io/ioutil"
	"mime/multipart"
	"os"
	"path"
	"strings"
)

type FileType int

const (
	TypeImage FileType = iota + 1
	TypeVideo
)

var TypeMap = map[FileType]string{
	TypeImage: "image",
	TypeVideo: "video",
}

func GetFileExt(name string) string {
	return path.Ext(name)
}

func GetFileName(name string) string {
	ext := GetFileExt(name)
	fileName := strings.TrimSuffix(name, ext)
	fileName = util.EncodeMD5(fileName)

	return fileName + ext
}

func GetSavePath() string {
	if len(setting.GetString("storage.path")) > 0 {
		return setting.GetString("storage.path")
	} else {
		return "./static/"
	}
}

func CheckSavePath(dst string) bool {
	_, err := os.Stat(dst)
	return os.IsNotExist(err)
}

func CheckContainExt(t FileType, name string) bool {
	ext := GetFileExt(name)
	ext = strings.ToUpper(ext)
	return true

	//switch t {
	//case TypeImage:
	//	for _, allowExt := range global.AppSetting.UploadImageAllowExts {
	//		if strings.ToUpper(allowExt) == ext {
	//			return true
	//		}
	//	}
	//case TypeVideo:
	//	return true
	//}
	//return false
}

func CheckMaxSize(t FileType, f multipart.File) bool {
	content, _ := ioutil.ReadAll(f)
	size := len(content)
	defaultSize := setting.GetInt("storage.UploadImgMaxSize")
	if defaultSize <= 0 {
		defaultSize = 10
	}
	switch t {
	case TypeImage:
		if size >= defaultSize*1024*1024 {
			return true
		}
	}

	return false
}

func CheckPermission(dst string) bool {
	_, err := os.Stat(dst)
	return os.IsPermission(err)
}

func CreateSavePath(dst string, perm os.FileMode) error {
	err := os.MkdirAll(dst, perm)
	if err != nil {
		return err
	}
	return nil
}

func SaveFile(file *multipart.FileHeader, dst string) error {
	src, err := file.Open()
	if err != nil {
		return err
	}
	defer src.Close()

	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, src)
	return err
}
